import store from '../store/index.js'

function fetch(obj){
	let url =obj.url;
	let method=obj.method;
	let data=obj.data

	let configHeader={
		"Content-Type": "application/x-www-form-urlencoded",
		"X-requested-With": "XMLHttpRequest"
	}
	if(data!==undefined && uni.getStorageSync("token")){
		data.access_token=uni.getStorageSync("token")
	}
	if(uni.getStorageSync('sessionId')){
		configHeader.Cookie = "PHPSESSID="+ uni.getStorageSync('sessionId')
	}
	if(url.indexOf('load-message')===-1){
		uni.showLoading({
			title: '加载中',
			mask: true
		});
	}

	return new Promise((resolve,reject)=>{
		uni.request({
			url:url,
			method:method,
			data:data,
			header: configHeader,
			dataType:'json',
			//这里是调用接口成功后的回调(2xx,3xx,4xx,都会进入这个success回调)
			success:(res)=> {
				uni.hideLoading();
				// console.log("success回调")
				// console.log(res.data)
				if (res.data.code === 0) {
					resolve(res.data)
				} else if (res.data.code === 20) { // token失效  重新登录
					if (store.state.token !== '') {
						// uni.showToast({
						// 	title:"登录失效",
						// 	icon:"success",
						// 	duration:2000
						// })
						setTimeout(() => {
							let user_lists = uni.getStorageSync("userLists")
							uni.clearStorageSync();
							uni.setStorageSync("userLists", user_lists)
							store.commit("SETTOKEN", '')
							store.commit("SET_USERINFO", '')
							uni.reLaunch({
								url: '/pages/login/login'
							})
						}, 1000)
					}


				}else if(res.data.code===10){
					uni.showToast({  //异常状态码直接在此处就弹出提示
						title: res.data.message,
						icon: "none",
						duration:3000
					})

			   }else{
					uni.showToast({  //异常状态码直接在此处就弹出提示
						title: res.data.message,
						icon: "none",
						duration:3000
					})
					// if(data.need_back!==undefined){
						resolve(res.data)
					// }else{
					// 	return
					// }



				}

				//这里面需要后台返回统一的数据格式
			},
			//这里是接口调用失败的回调(一般没有网,或者服务端没开启服务就会进入fail回调)
			fail:(err)=>{

				console.log("fail回调")
				uni.showToast({
					title:"网络异常",
					icon:none
				})
				reject("网络异常")
			}
		})
	})
}

export const GET=function (url,data){
	return fetch({
		url:url,
		method:"get",
		data:data,
		timeOut:5000 //请求延迟,如果超过5秒,这个请求将会中断,请求失败
	})
}
export const POST=function (url,data){
	return fetch({
		url:url,
		method:"post",
		data:data,
		timeOut:5000
	})
}


